package com.le.tester.book.concurrentjavafight.l_14;

import org.omg.CORBA.PUBLIC_MEMBER;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * createTime：2024/5/23 15:57
 * description：使用lock来实现信号量
 */
public class SemaphoreOnLock {

    private final Lock lock = new ReentrantLock();

    private final Condition condition = lock.newCondition();

    private int permits;

    public SemaphoreOnLock(int initPermits) {
        lock.lock();
        try {
            permits = initPermits;
        } finally {
            lock.unlock();
        }
    }

    public void acquire() throws InterruptedException {

        lock.lock();
        try {
            while (permits <= 0) {
                condition.await();
            }
            --permits;
        } finally {
            lock.unlock();
        }
    }

    public void release() {
        lock.lock();
        try {
            ++permits;
            condition.signal();
        } finally {
            lock.unlock();
        }
    }
}
